//
//  AddCarViewController.m
//  HaierGMS_APP
//
//  Created by 堂堂 on 16/10/14.
//  Copyright © 2016年 堂堂. All rights reserved.
//

#import "AddCarViewController.h"
#import "UIColor+Hex.h"
#import <AliyunOSSiOS/OSSService.h>
#import "MBProgressHUD+MJ.h"
#import "UserDefaultUtil.h"
#import "HttpReauestParam.h"
#import "AFHTTPRequestOperationManager.h"
#import "CarTypeViewController.h"
#import "AuthViewController.h"
#define ScreenHeight [[UIScreen mainScreen] bounds].size.height//获取屏幕高度，兼容性测试
#define ScreenWidth [[UIScreen mainScreen] bounds].size.width//获取屏幕宽度，兼容性测试

@interface AddCarViewController ()

@property NSArray *images;
@property NSInteger add_image_pos;
@property NSString *photo1;
@property NSString *photo2;
@property NSString *license;

@end

@implementation AddCarViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.limit_button setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.limit_button setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#ff7e00"]] forState:UIControlStateNormal];
    [self.limit_button setBackgroundImage:[self createImageWithColor:[UIColor colorWithHexString:@"#55ff7e00"]] forState:UIControlStateSelected];
    [self.limit_button addTarget:self action:@selector(limitClick) forControlEvents:UIControlEventTouchUpInside];
    
    
    self.car_field.delegate = self;
    
    _text1.textColor = [UIColor colorWithHexString:@"#ff7e00"];
    _text2.textColor = [UIColor colorWithHexString:@"#ff7e00"];
    
    self.contentView.backgroundColor = [UIColor colorWithHexString:@"#f2f2f2"];
    
    [_car_content addTarget:self action:@selector(addCarClick) forControlEvents:UIControlEventTouchUpInside];
    
    
//    int widget = (ScreenWidth - 120) / 3;
//    
//    
//    _image_content1 = [[UIControl alloc]initWithFrame:CGRectMake(60 + widget, 15, widget, 80)];
//    _image_content2 = [[UIControl alloc]initWithFrame:CGRectMake(90 + widget * 2, 15, widget, 80)];
//    
//    _image_content1.tag = 21;
//    _image_content2.tag = 22;
//    
//    [_images_contentView addSubview:_image_content1];
//    [_images_contentView addSubview:_image_content2];
//    
//    _car_image1 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, 111, 80)];
//    _car_image2 = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, _image_content2.frame.size.width, _image_content2.frame.size.height)];
//    
//    _car_image1.contentMode = UIViewContentModeCenter;
//    _car_image2.contentMode = UIViewContentModeCenter;
//    
//    _car_image1.image = [UIImage imageNamed:@"auth_car_left_image"];
//    _car_image2.image = [UIImage imageNamed:@"auth_car_right_image"];
//    [_image_content1 addSubview:_car_image1];
//    [_image_content2 addSubview:_car_image2];
//    
//
//    [_image_content1 addTarget:self action:@selector(image_click:) forControlEvents:UIControlEventTouchUpInside];
//    [_image_content2 addTarget:self action:@selector(image_click:) forControlEvents:UIControlEventTouchUpInside];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (IBAction)image_click:(id)sender {
    UIView *view = sender;
    
    _add_image_pos = view.tag;
    [self callActionSheetFunc];
}

- (UIImage*) createImageWithColor: (UIColor*) color
{
    CGRect rect=CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage*theImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return theImage;
}

-(void)limitClick{
    _license = _car_field.text;
    
    if(_photo1 == nil || [_photo1 isEqualToString:@""]){
        [MBProgressHUD showError:@"请上传照片"];
        return;
    }
    if(_photo2 == nil || [_photo2 isEqualToString:@""]){
        [MBProgressHUD showError:@"请上传照片"];
        return;
    }
    if(_license == nil || [_license isEqualToString:@""]){
        [MBProgressHUD showError:@"请填写车牌号"];
        return;
    }
    if(_type == nil || [_type isEqualToString:@""]){
        [MBProgressHUD showError:@"请选择车辆类型"];
        return;
    }
    
    NSDictionary *dic= @{@"photos1":_photo1,@"photos2":_photo2,@"license":_license,@"type":_type};
    
    AuthViewController *vc = self.navigationController.viewControllers[self.navigationController.viewControllers.count - 2];
    [vc.auth_cars addObject:dic];
    [self.navigationController popToViewController:vc animated:YES];
    
}

-(void)viewDidAppear:(BOOL)animated{
    if (_type != nil && ![_type isEqualToString:@""]) {
        _typeLab.text = _type;
    }
    [super viewDidAppear:animated];
}
- (IBAction)touchView:(id)sender {
    [self.view endEditing:YES];
}

-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    if([textField isFirstResponder]){
        [textField  resignFirstResponder];
    }
    return YES;
}

/**
 @ 调用ActionSheet
 */
- (void)callActionSheetFunc{
    

    
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"拍照", @"从相册选择",  nil];
    }else{
        self.actionSheet = [[UIActionSheet alloc] initWithTitle:@"选择图像" delegate:self cancelButtonTitle:@"取消"destructiveButtonTitle:nil otherButtonTitles:@"从相册选择",  nil];
    }
    
    self.actionSheet.tag = 1000;
    [self.actionSheet showInView:self.view];
}

// Called when a button is clicked. The view will be automatically dismissed after this call returns
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (actionSheet.tag == 1000) {
        NSUInteger sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        // 判断是否支持相机
        if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            switch (buttonIndex) {
                case 0:
                    //来源:相机
                    sourceType = UIImagePickerControllerSourceTypeCamera;
                    break;
                case 1:
                    //来源:相册
                    sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
                    break;
                case 2:
                    return;
            }
        }
        else {
            if (buttonIndex == 2) {
                return;
            } else {
                sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
            }
        }
        // 跳转到相机或相册页面
        UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
        imagePickerController.delegate = self;
        imagePickerController.allowsEditing = YES;
        imagePickerController.sourceType = sourceType;
        
        [self presentViewController:imagePickerController animated:YES completion:^{
            
        }];
    }
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:^{
        
    }];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
    UIImage *image2 = [self scaleToSize:image size:CGSizeMake(90, 76)];
    //获得的图片
    if (_add_image_pos == 21) {
       // _car_image1.frame = CGRectMake(0, 0, _car_image1.frame.size.width, _car_image1.frame.size.height) ;
        [_car_image1 setImage:image2];
    }
    if (_add_image_pos == 22) {
       // _car_image2.frame = CGRectMake(0, 0, _car_image2.frame.size.width, _car_image2.frame.size.height) ;
        [_car_image2 setImage:image2];
    }
    
    NSData *imgData = UIImageJPEGRepresentation(image, 1.0);
    [self uploadImage:imgData];
    
    
}
-(void)addCarClick{
    UIStoryboard *sb = [UIStoryboard storyboardWithName:@"App_Main" bundle:[NSBundle mainBundle]];
    CarTypeViewController *vc = [sb instantiateViewControllerWithIdentifier:@"auth_car_type_view"];
    [self.navigationController pushViewController:vc animated:YES];
}

- (IBAction)view_touch:(id)sender {
    [self.view endEditing:YES];
}

-(void)uploadImage:(NSData *)img{
    
    
    
    id<OSSCredentialProvider> credential = [[OSSPlainTextAKSKPairCredentialProvider alloc] initWithPlainTextAccessKey: OOS_KEY_ID secretKey:OOS_KEY_SCERET];
    
    OSSClient *client = [[OSSClient alloc] initWithEndpoint:@"http://oss-cn-shanghai.aliyuncs.com" credentialProvider:credential];
    
    OSSPutObjectRequest * put = [OSSPutObjectRequest new];
    
    // 必填字段
    put.bucketName = OOS_KEY_BUCKET;
    
    NSString *filePath = [NSString stringWithFormat:@"%@.png",[self getUniqueStrByUUID]];
    
    
    put.objectKey = filePath;
    
    if (_add_image_pos == 21) {
        _photo1 = [NSString stringWithFormat:@"http://%@.oss-cn-shanghai.aliyuncs.com/%@",OOS_KEY_BUCKET,filePath];
    }
    if (_add_image_pos == 22) {
        _photo2 = [NSString stringWithFormat:@"http://%@.oss-cn-shanghai.aliyuncs.com/%@",OOS_KEY_BUCKET,filePath];
    }
    // put.uploadingFileURL = [NSURL fileURLWithPath:@"<filepath>"];
    put.uploadingData = img; // 直接上传NSData
    
    // 可选字段，可不设置
    put.uploadProgress = ^(int64_t bytesSent, int64_t totalByteSent, int64_t totalBytesExpectedToSend) {
        // 当前上传段长度、当前已经上传总长度、一共需要上传的总长度
        NSLog(@"%lld, %lld, %lld", bytesSent, totalByteSent, totalBytesExpectedToSend);
    };
    
    // 以下可选字段的含义参考： https://docs.aliyun.com/#/pub/oss/api-reference/object&PutObject
    // put.contentType = @"";
    // put.contentMd5 = @"";
    // put.contentEncoding = @"";
    // put.contentDisposition = @"";
    
    // put.objectMeta = [NSMutableDictionary dictionaryWithObjectsAndKeys:@"value1", @"x-oss-meta-name1", nil]; // 可以在上传时设置元信息或者其他HTTP头部
    
    [MBProgressHUD showMessage:@"上传图片"];
    OSSTask * putTask = [client putObject:put];
    
    [putTask continueWithBlock:^id(OSSTask *task) {
        
        if (!task.error) {
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                NSLog(@"上传图片结果22");
                [MBProgressHUD hideHUD];
                
                
                NSLog(@"upload object success111!");
            });
            
            NSLog(@"upload object success222!");
        } else {
            dispatch_sync(dispatch_get_main_queue(), ^{
                //Update UI in UI thread here
                
                [MBProgressHUD hideHUD];
                
                if (_add_image_pos == 21) {
                    _car_image1.image = [UIImage imageNamed:@"auth_car_left_image"];
                }
                if (_add_image_pos == 22) {
                    _car_image2.image = [UIImage imageNamed:@"auth_car_right_image"];
                }
            });
        }
        
        
        return nil;
    }];
}
- (NSString *)getUniqueStrByUUID
{
    CFUUIDRef    uuidObj = CFUUIDCreate(nil);//create a new UUID
    
    //get the string representation of the UUID
    
    NSString    *uuidString = (__bridge_transfer NSString *)CFUUIDCreateString(nil, uuidObj);
    
    CFRelease(uuidObj);
    
    return uuidString ;
    
}
- (IBAction)back_click:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (UIImage *)scaleToSize:(UIImage *)img size:(CGSize)size{
         // 创建一个bitmap的context
         // 并把它设置成为当前正在使用的context
         UIGraphicsBeginImageContext(size);
         // 绘制改变大小的图片
         [img drawInRect:CGRectMake(0, 0, size.width, size.height)];
         // 从当前context中创建一个改变大小后的图片
         UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
         // 使当前的context出堆栈
         UIGraphicsEndImageContext();
         // 返回新的改变大小后的图片
         return scaledImage;
     }
@end
